//
//  PHLoginViewController.m
//  PhnixHome
//
//  Created by Levy Xu on 2017/12/20.
//  Copyright © 2017年 Levy Xu. All rights reserved.
//

#import "PHLoginViewController.h"
#import "WXApi.h"
#import "WXApiObject.h"
#import "WXConst.h"
#import "PHRegisterViewController.h"

@interface PHLoginViewController ()<QMUINavigationControllerDelegate, QMUITextFieldDelegate>
@property(nonatomic, strong) UIImageView *imageView;
@property(nonatomic, strong) QMUITextField *nameTextField;
@property(nonatomic, strong) QMUITextField *pwdTextField;

@property(nonatomic, strong) QMUIFillButton *loginBtn;
@property(nonatomic, strong) QMUIButton *forgetBtn;
@property(nonatomic, strong) QMUIButton *registerBtn;

@property(nonatomic, strong) QMUILabel *otherLabel;
@property(nonatomic, strong) QMUIButton *wechatBtn;
@property(nonatomic, strong) CALayer *separatorLayer3;
@property(nonatomic, strong) CALayer *separatorLayer4;
@end

@implementation PHLoginViewController

-(void)dealloc {
    [NNCDC removeObserver:self];
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [NNCDC addObserver:self selector:@selector(WXLogin:) name:@"WXAuthorizationSuccess" object:nil];
    }
    return self;
}

- (void)initSubviews {
    [super initSubviews];
    
    _imageView = [[UIImageView alloc] initWithImage:UIImageMake(@"phnix_red")];
    [self.view addSubview:_imageView];
    
    _nameTextField = [[QMUITextField alloc] init];
    _nameTextField.borderStyle = UITextBorderStyleNone;
    _nameTextField.returnKeyType = UIReturnKeyDone;
    _nameTextField.backgroundColor = UIColorClear;
    _nameTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _nameTextField.font = CodeFontMake(14);
    _nameTextField.textColor = UIColorBlack;
    _nameTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _nameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _nameTextField.placeholder = NSLocalizedString(@"tips_input_username", nil);
    _nameTextField.delegate = self;
    _nameTextField.qmui_borderPosition = QMUIBorderViewPositionBottom;
    _nameTextField.enablesReturnKeyAutomatically = YES;
//    [_nameTextField addTarget:self action:@selector(updateSubmitButtonEnables) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:_nameTextField];
    
    UIImageView *nameIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    nameIV.image = UIImageMake(@"login_user");
    _nameTextField.leftViewMode = UITextFieldViewModeAlways;
    _nameTextField.leftView = nameIV;
    
    
    _pwdTextField = [[QMUITextField alloc] init];
    _pwdTextField.borderStyle = UITextBorderStyleNone;
    _pwdTextField.returnKeyType = UIReturnKeyDone;
    _pwdTextField.backgroundColor = UIColorClear;
    _pwdTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _pwdTextField.font = CodeFontMake(14);
    _pwdTextField.textColor = UIColorBlack;
    _pwdTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _pwdTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _pwdTextField.placeholder = NSLocalizedString(@"tips_input_password", nil);
    _pwdTextField.secureTextEntry = YES;
    _pwdTextField.delegate = self;
    _pwdTextField.qmui_borderPosition = QMUIBorderViewPositionBottom;
    _pwdTextField.enablesReturnKeyAutomatically = YES;
//    [_pwdTextField addTarget:self action:@selector(updateSubmitButtonEnables) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:_pwdTextField];
    
    UIImageView *pwdIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    pwdIV.image = UIImageMake(@"login_pwd");
    _pwdTextField.leftViewMode = UITextFieldViewModeAlways;
    _pwdTextField.leftView = pwdIV;
    
    QMUIButton *eyeBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [eyeBtn setImage:UIImageMake(@"eye_close") forState:UIControlStateNormal];
    [eyeBtn setImage:UIImageMake(@"eye_open") forState:UIControlStateSelected];
    [eyeBtn addTarget:self action:@selector(eyeAction:) forControlEvents:UIControlEventTouchUpInside];
    _pwdTextField.rightViewMode = UITextFieldViewModeAlways;
    _pwdTextField.rightView = eyeBtn;
    
    
    _loginBtn = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorRed];
    _loginBtn.titleLabel.font = CodeFontMake(16);
    [_loginBtn setTitle:NSLocalizedString(@"btn_sign_in", nil) forState:UIControlStateNormal];
    [_loginBtn addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_loginBtn];
    
    _forgetBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    _forgetBtn.titleLabel.font = CodeFontMake(14);
    _forgetBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_forgetBtn setTitleColor:[UIColor qmui_colorWithHexString:@"3e3838"] forState:UIControlStateNormal];
    [_forgetBtn setTitle:NSLocalizedString(@"btn_forget_password", nil) forState:UIControlStateNormal];
    [_forgetBtn addTarget:self action:@selector(forgetAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_forgetBtn];
    
    _registerBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    _registerBtn.titleLabel.font = CodeFontMake(14);
    _registerBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [_registerBtn setTitleColor:[UIColor qmui_colorWithHexString:@"3e3838"] forState:UIControlStateNormal];
    [_registerBtn setTitle:NSLocalizedString(@"btn_sign_up", nil) forState:UIControlStateNormal];
    [_registerBtn addTarget:self action:@selector(registerAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_registerBtn];
    
    
    _otherLabel = [[QMUILabel alloc] init];
    _otherLabel.textColor = [UIColor qmui_colorWithHexString:@"3e3838"];
    _otherLabel.font = CodeFontMake(14);
    _otherLabel.textAlignment = NSTextAlignmentCenter;
    _otherLabel.text = NSLocalizedString(@"tips_other_login_method", nil);
    [self.view addSubview:_otherLabel];
    
    _separatorLayer3 = [QDCommonUI generateSeparatorLayer];
    _separatorLayer3.backgroundColor = [UIColor qmui_colorWithHexString:@"3e3838"].CGColor;
    [self.view.layer addSublayer:_separatorLayer3];
    
    _separatorLayer4 = [QDCommonUI generateSeparatorLayer];
    _separatorLayer4.backgroundColor = [UIColor qmui_colorWithHexString:@"3e3838"].CGColor;
    [self.view.layer addSublayer:_separatorLayer4];
    
    _wechatBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [_wechatBtn setBackgroundImage:UIImageMake(@"login_wechat") forState:UIControlStateNormal];
    [_wechatBtn addTarget:self action:@selector(wechatLogin) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_wechatBtn];
    
    if ([NDSUD objectForKey:@"kLastLoginUserName"]) {
        _nameTextField.text = [NDSUD objectForKey:@"kLastLoginUserName"];
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    _imageView.frame = CGRectMake(SCREEN_WIDTH / 2 - 80, self.qmui_navigationBarMaxYInViewCoordinator + 80, 160, 60);
    
    _nameTextField.frame = CGRectMake(30.0f, _imageView.qmui_bottom + 30, SCREEN_WIDTH - 2 * 30.0f, 40);
    
    _pwdTextField.frame = CGRectMake(_nameTextField.qmui_left, _nameTextField.qmui_bottom + 10, SCREEN_WIDTH - 60, 40);
    
    _loginBtn.frame = CGRectMake(_nameTextField.qmui_left, _pwdTextField.qmui_bottom + 30, _pwdTextField.qmui_width, 40);
    
    _forgetBtn.frame = CGRectMake(_nameTextField.qmui_left, _loginBtn.qmui_bottom + 20, 120, 20);
    _registerBtn.frame = CGRectMake(_nameTextField.qmui_right - 120, _forgetBtn.qmui_top, 120, 20);
    
    
    CGSize size = [_otherLabel sizeThatFits:CGSizeMake(_nameTextField.qmui_width, 20)];
    _otherLabel.qmui_width = size.width;
    _otherLabel.qmui_height = size.height;
    _otherLabel.center = CGPointMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT - 90 - IPhoneXSafeAreaInsets.bottom);
    
    _separatorLayer3.frame = CGRectMake(_nameTextField.qmui_left, _otherLabel.center.y, _otherLabel.qmui_left - _nameTextField.qmui_left, PixelOne);
    _separatorLayer4.frame = CGRectMake(_otherLabel.qmui_right, _otherLabel.center.y, _nameTextField.qmui_right - _otherLabel.qmui_right, PixelOne);
    
    _wechatBtn.frame = CGRectMake(SCREEN_WIDTH / 2 - 25, _otherLabel.qmui_bottom + 15, 50, 50);
}

-(void)eyeAction:(QMUIButton *)sender {
    sender.selected = !sender.isSelected;
    _pwdTextField.secureTextEntry = !sender.isSelected;
}

-(void)loginAction:(id)sender {
    NSString *username = _nameTextField.text;
    NSString *password = _pwdTextField.text;
    
    if (![NSString dd_checkMobileNumber:username] && ![NSString dd_checkEmail:username]) {
        [KKAlert warningWithText:NSLocalizedString(@"tips_check_username", nil)];
        return;
    }
    if (![NSString dd_checkPassword:password]) {
        [KKAlert warningWithText:NSLocalizedString(@"tips_check_password", nil)];
        return;
    }
    
    PHAccountType type = [NetUtils typeWithName:username];
    [NetUtils loginWithType:type name:username password:password finish:nil];
}

-(void)forgetAction:(id)sender {
    PHRegisterViewController *registerVC = [[PHRegisterViewController alloc] initWithMethod:PHMethodForgetPWD];
    [self.navigationController pushViewController:registerVC animated:YES];
}

-(void)registerAction:(id)sender {
    PHRegisterViewController *registerVC = [[PHRegisterViewController alloc] initWithMethod:PHMethodRegister];
    [self.navigationController pushViewController:registerVC animated:YES];
}

-(void)wechatLogin {
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq *request = [[SendAuthReq alloc] init];
        request.state = @"phnix_home_weixin_login";
        request.scope = @"snsapi_userinfo";
        [WXApi sendReq:request];
    } else {
        [KKHUD showError:@"登陆失败，请使用手机号或邮箱登录"];
    }
}

-(void)WXLogin:(NSNotification *)notification {
    
    NSDictionary *paras = @{ @"appid": WX_AppID, @"secret": WX_Secret, @"code": notification.object[@"code"], @"grant_type": @"authorization_code" };
    
    WS(ws);
    [[self WXManager] GET:WX_ACCESS_TOKEN_URL parameters:paras progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dict = [responseObject mj_JSONObject];
        LOG(@"dict %@",dict);
        
        [ws requestUserInfoByToken:dict[@"access_token"] andOpenid:dict[@"openid"]];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        LOG(@"error %@",error.description);
    }];
}

-(void)requestUserInfoByToken:(NSString *)token andOpenid:(NSString *)openID {
    
    NSDictionary *paras = @{ @"openid": openID, @"access_token": token };
    
    WS(ws);
    [[self WXManager] GET:WX_USERINFO_URL parameters:paras progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [responseObject mj_JSONObject];
        LOG(@"dict %@",dict);
        
        [NDSUD setObject:dict forKey:@"WXSaveUserInfo"];
        
        [NetUtils loginWithType:PHAccountTypeWechat name:openID password:nil finish:^(BOOL success) {
            if (!success) {
                [KKHUD hide];
                
                PHRegisterViewController *registerVC = [[PHRegisterViewController alloc] initWithMethod:PHMethodBindWechat];
                registerVC.third_id = openID;
                [ws.navigationController pushViewController:registerVC animated:YES];
            }
        }];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        LOG(@"error %@",error.description);
    }];
}

-(AFHTTPSessionManager *)WXManager {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSMutableSet *set = [manager.responseSerializer.acceptableContentTypes mutableCopy];
    [set addObject:@"text/plain"];
    manager.responseSerializer.acceptableContentTypes = set;
    return manager;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
//    [self updateSubmitButtonEnables];
    
    if (![WXApi isWXAppInstalled]) {
        _otherLabel.hidden = YES;
        _separatorLayer3.hidden = YES;
        _separatorLayer4.hidden = YES;
        _wechatBtn.hidden = YES;
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)updateSubmitButtonEnables {
    self.loginBtn.enabled = ([NSString dd_checkMobileNumber:_nameTextField.text] || [NSString dd_checkEmail:_nameTextField.text]) && [NSString dd_checkPassword:_pwdTextField.text];
}

#pragma mark - QMUINavigationControllerDelegate
- (BOOL)shouldSetStatusBarStyleLight {
    return NO;
}

#pragma mark - UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    return YES;
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
